#!/usr/bin/env node

/**
 * Simple Web Config Server
 *
 * 轻量级Web配置服务器，用于本地MCP工具
 * 提供基本的Web界面进行API密钥配置
 */

const http = require('http');
const fs = require('fs');
const path = require('path');

class SimpleWebConfigServer {
    constructor() {
        this.port = 37251; // 固定端口，简化端口管理
        this.server = null;
        this.isRunning = false;
        this.configDir = null;
        this.options = null;
    }

    /**
     * 加载配置
     */
    loadConfig() {
        const config = {
            currentProviderModel: '',
            moonshot: { apiKey: '', baseUrl: 'https://api.moonshot.cn/v1' },
            tencent: { apiKey: '', baseUrl: 'https://api.hunyuan.cloud.tencent.com/v1' },
            zai: { apiKey: '', baseUrl: 'https://open.bigmodel.cn/api/paas/v4' },
            custom: { name: '', apiKey: '', baseUrl: '' }
        };

        try {
            const JsonConfigManager = require('./lib/config/json-config-manager');
            const ConfigPathResolver = require('./lib/config/config-path-resolver');

            const pathResolver = new ConfigPathResolver();
            const configManager = new JsonConfigManager(this.configDir || process.cwd());

            const configPathInfo = pathResolver.getBestConfigPath(this.configDir || process.cwd());
            if (configPathInfo) {
                configManager.configPath = configPathInfo.path;
                const jsonConfig = configManager.loadConfig();

                config.currentProviderModel = jsonConfig.current_provider_model || '';

                if (jsonConfig.providers) {
                    for (const [providerName, providerConfig] of Object.entries(jsonConfig.providers)) {
                        if (config[providerName]) {
                            config[providerName].apiKey = providerConfig.api_key || '';
                            config[providerName].baseUrl = providerConfig.base || '';
                        }
                    }
                }
            }
        } catch (error) {
            console.log('加载配置失败，使用默认配置');
        }

        return config;
    }

    /**
     * 保存配置
     */
    saveConfig() {
        try {
            const jsonConfig = {
                version: "1.0.0",
                current_provider_model: this.config.currentProviderModel,
                providers: {}
            };

            const providers = ['moonshot', 'tencent', 'zai', 'custom'];
            for (const provider of providers) {
                if (this.config[provider].apiKey) {
                    jsonConfig.providers[provider] = {
                        api_key: this.config[provider].apiKey,
                        base: this.config[provider].baseUrl,
                        models: [{
                            id: provider === 'moonshot' ? 'moonshot-v1-8k-vision-preview' :
                                provider === 'tencent' ? 'hunyuan-vision' :
                                provider === 'zai' ? 'glm-4.5v' : `${provider}-model`,
                            name: provider === 'moonshot' ? 'Moonshot Vision 8K' :
                                provider === 'tencent' ? 'Hunyuan Vision' :
                                provider === 'zai' ? 'GLM-4.5 Vision' : `${provider} Model`,
                            type: "vision",
                            capabilities: ["image_analysis"],
                            max_tokens: 8192,
                            supports_vision: true,
                            enabled: true
                        }],
                        timeout: 30000,
                        max_retries: 3
                    };
                }
            }

            const JsonConfigManager = require('./lib/config/json-config-manager');
            const ConfigPathResolver = require('./lib/config/config-path-resolver');

            const pathResolver = new ConfigPathResolver();
            const configManager = new JsonConfigManager(this.configDir || process.cwd());

            const configPathInfo = pathResolver.getBestConfigPath(this.configDir || process.cwd());
            if (configPathInfo) {
                configManager.configPath = configPathInfo.path;
                configManager.saveConfig(jsonConfig);
                return true;
            }
        } catch (error) {
            console.log('Failed to save configuration:', error.message);
            return false;
        }
    }

    /**
     * 加载美观的配置页面
     */
    loadConfigPage() {
        try {
            // 始终使用项目根目录，而不是配置目录
            const projectRoot = process.cwd();
            // 优先使用主配置页面（这是完整的美观版本）
            let htmlPath = path.join(projectRoot, 'config-page.html');
            console.log(`🔍 使用主配置页面: ${htmlPath}`);

            if (!fs.existsSync(htmlPath)) {
                console.log(`⚠️ 主配置页面不存在，使用备用美观版本`);
                // 备用方案：使用config-page-beautiful.html
                htmlPath = path.join(projectRoot, 'config-page-beautiful.html');
            }

            if (!fs.existsSync(htmlPath)) {
                throw new Error(`Configuration page not found: ${htmlPath}`);
            }

            console.log(`✅ 加载配置页面: ${htmlPath}`);

            const htmlTemplate = fs.readFileSync(htmlPath, 'utf8');

            // 替换模板中的占位符
            let html = htmlTemplate
                .replace(/{{moonshotApiKey}}/g, this.config.moonshot.apiKey || '')
                .replace(/{{tencentApiKey}}/g, this.config.tencent.apiKey || '')
                .replace(/{{zaiApiKey}}/g, this.config.zai.apiKey || '')
                .replace(/{{customApiKey}}/g, this.config.custom.apiKey || '')
                .replace(/{{customName}}/g, this.config.custom.name || '')
                .replace(/{{customBaseUrl}}/g, this.config.custom.baseUrl || '')
                .replace(/{{currentModel}}/g, this.config.currentProviderModel || '');

            return html;
        } catch (error) {
            console.error('Failed to load config page:', error.message);
            return `<h1>配置页面加载失败</h1><p>错误: ${error.message}</p>`;
        }
    }

    /**
     * 处理API请求
     */
    handleRequest(req, res) {
        const url = req.url;
        const method = req.method;

        // 设置CORS头
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

        if (method === 'OPTIONS') {
            res.writeHead(200);
            res.end();
            return;
        }

        if (url === '/' && method === 'GET') {
            res.setHeader('Content-Type', 'text/html; charset=utf-8');
            res.writeHead(200);
            res.end(this.loadConfigPage());
        } else if (url === '/manage' && method === 'GET') {
            // 处理管理界面请求 - 返回美观的HTML页面
            const managePagePath = path.join(process.cwd(), 'manage.html');
            if (fs.existsSync(managePagePath)) {
                const managePage = fs.readFileSync(managePagePath, 'utf8');
                res.setHeader('Content-Type', 'text/html; charset=utf-8');
                res.writeHead(200);
                res.end(managePage);
            } else {
                // 如果没有管理界面页面，返回JSON数据作为备用
                res.setHeader('Content-Type', 'application/json; charset=utf-8');
                res.writeHead(200);
                res.end(JSON.stringify({
                    success: true,
                    message: '管理界面功能',
                    currentConfig: this.config,
                    providers: {
                        moonshot: {
                            name: 'Moonshot (月之暗面)',
                            models: ['moonshot-v1-8k-vision-preview'],
                            baseUrl: 'https://api.moonshot.cn/v1'
                        },
                        tencent: {
                            name: 'Tencent (腾讯混元)',
                            models: ['hunyuan-vision'],
                            baseUrl: 'https://api.hunyuan.cloud.tencent.com/v1'
                        },
                        zai: {
                            name: 'Zhipu AI (智谱AI)',
                            models: ['glm-4.5v'],
                            baseUrl: 'https://open.bigmodel.cn/api/paas/v4'
                        }
                    }
                }));
            }
        } else if (url === '/api/manage-data' && method === 'GET') {
            // 处理管理界面API数据请求
            res.setHeader('Content-Type', 'application/json; charset=utf-8');
            res.writeHead(200);
            res.end(JSON.stringify({
                success: true,
                message: '管理界面功能',
                currentConfig: this.config,
                providers: {
                    moonshot: {
                        name: 'Moonshot (月之暗面)',
                        models: ['moonshot-v1-8k-vision-preview'],
                        baseUrl: 'https://api.moonshot.cn/v1'
                    },
                    tencent: {
                        name: 'Tencent (腾讯混元)',
                        models: ['hunyuan-vision'],
                        baseUrl: 'https://api.hunyuan.cloud.tencent.com/v1'
                    },
                    zai: {
                        name: 'Zhipu AI (智谱AI)',
                        models: ['glm-4.5v'],
                        baseUrl: 'https://open.bigmodel.cn/api/paas/v4'
                    }
                }
            }));
        } else if (url === '/api/config' && method === 'POST') {
            let body = '';
            req.on('data', chunk => {
                body += chunk.toString();
            });
            req.on('end', () => {
                try {
                    const newConfig = JSON.parse(body);

                    // 更新配置
                    this.config = { ...this.config, ...newConfig };

                    // 设置当前模型（优先使用第一个有API密钥的提供商）
                    const providers = ['moonshot', 'tencent', 'zai', 'custom'];
                    for (const provider of providers) {
                        if (this.config[provider].apiKey) {
                            this.config.currentProviderModel = provider === 'moonshot' ? 'moonshot-v1-8k-vision-preview' :
                                provider === 'tencent' ? 'hunyuan-vision' :
                                provider === 'zai' ? 'glm-4.5v' : `${provider}-model`;
                            break;
                        }
                    }

                    // 保存配置
                    if (this.saveConfig()) {
                        res.writeHead(200, { 'Content-Type': 'application/json' });
                        res.end(JSON.stringify({
                            success: true,
                            currentModel: this.config.currentProviderModel,
                            message: '配置保存成功'
                        }));
                    } else {
                        res.writeHead(500, { 'Content-Type': 'application/json' });
                        res.end(JSON.stringify({
                            success: false,
                            error: '配置保存失败'
                        }));
                    }
                } catch (error) {
                    res.writeHead(400, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({
                        success: false,
                        error: '无效的配置数据'
                    }));
                }
            });
        } else {
            res.writeHead(404);
            res.end('Not Found');
        }
    }

    /**
     * 启动服务器 - 兼容应用程序API
     */
    async start(configDir, options = {}) {
        this.configDir = configDir;
        this.options = options;
        this.config = this.loadConfig();

        return new Promise((resolve, reject) => {
            try {
                this.server = http.createServer((req, res) => {
                    this.handleRequest(req, res);
                });

                this.server.listen(this.port, () => {
                    this.isRunning = true;
                    console.log(`🚀 Web配置服务器启动成功`);
                    console.log(`📱 访问 http://localhost:${this.port} 进行配置`);
                    console.log(`⏹ 按 Ctrl+C 停止服务器`);

                    // 如果启用了autoOpen，尝试打开浏览器
                    if (this.options && this.options.autoOpen) {
                        this.openBrowser();
                    }

                    resolve();
                });

                this.server.on('error', (error) => {
                    reject(error);
                });

                // 优雅关闭
                process.on('SIGINT', () => {
                    console.log('\n👋 正在关闭服务器...');
                    this.server.close(() => {
                        console.log('✅ 服务器已关闭');
                        process.exit(0);
                    });
                });
            } catch (error) {
                reject(error);
            }
        });
    }

    /**
     * 获取服务器URL
     */
    getUrl() {
        return `http://localhost:${this.port}`;
    }

    /**
     * 获取服务器配置
     */
    getConfig() {
        return {
            port: this.port,
            url: this.getUrl(),
            configDir: this.configDir,
            isRunning: this.isRunning
        };
    }

    /**
     * 打开浏览器
     */
    openBrowser() {
        try {
            const { exec } = require('child_process');
            const url = this.getUrl();

            // 根据操作系统选择命令
            const startCmd = process.platform === 'win32' ? 'start' :
                           process.platform === 'darwin' ? 'open' : 'xdg-open';

            exec(`${startCmd} ${url}`, (error) => {
                if (error) {
                    console.log(`无法自动打开浏览器: ${error.message}`);
                }
            });
        } catch (error) {
            console.log(`无法打开浏览器: ${error.message}`);
        }
    }

    /**
     * 停止服务器
     */
    async stop() {
        if (this.server && this.isRunning) {
            return new Promise((resolve) => {
                this.server.close(() => {
                    this.isRunning = false;
                    console.log('✅ Web配置服务器已停止');
                    resolve();
                });
            });
        }
    }
}

// 主程序
if (require.main === module) {
    const configDir = process.argv[2] || process.cwd();
    const server = new SimpleWebConfigServer();
    server.start(configDir, { autoOpen: true }).catch(error => {
        console.error('启动配置服务器失败:', error.message);
        process.exit(1);
    });
}

module.exports = SimpleWebConfigServer;